package com.sai.jsai.module.auth.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.sai.jsai.common.base.exception.CommonBizException;
import com.sai.jsai.module.auth.domain.vo.LoginReqVO;
import com.sai.jsai.module.auth.domain.vo.LoginRespVO;
import com.sai.jsai.module.auth.handler.AuthErrorCode;
import com.sai.jsai.module.auth.service.AuthService;
import com.sai.jsai.module.system.api.SysUserApi;
import com.sai.jsai.module.system.api.dto.SysUserRespDTO;
import com.sai.jsai.module.system.api.dto.SysUserRolePermissionDTO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

/**
 * @author jisai
 * @version 0.0.1
 * @Description TODO
 * @createTime 2024/10/01
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    SysUserApi sysUserApi;

    @Override
    public LoginRespVO login(LoginReqVO loginReqVO) {
        SysUserRespDTO sysUser = sysUserApi.getByUsername(loginReqVO.getUsername());
        // 用户名不存在
        if (sysUser == null) {
            throw new CommonBizException(AuthErrorCode.AUTH_LOGIN_USERNAME_NOT_EXIST);
        }
        // 密码错误
        if (!BCrypt.checkpw(loginReqVO.getPassword(), sysUser.getPassword())) {
            throw new CommonBizException(AuthErrorCode.AUTH_LOGIN_PASSWORD_ERROR);
        }
        // sa-token 登录
        StpUtil.login(sysUser.getUsername());
        StpUtil.getTokenSession().set(SaSession.USER, sysUser);

        LoginRespVO loginRespVO = new LoginRespVO();
        loginRespVO.setUserId(sysUser.getId());
        loginRespVO.setUsername(sysUser.getUsername());
        loginRespVO.setToken(StpUtil.getTokenValue());
        loginRespVO.setTokenExpiration(StpUtil.getTokenTimeout());
        return loginRespVO;
    }

    /**
     * 获取当前登录用户信息
     *
     * @return 当前登录用户信息
     */
    @Override
    public SysUserRespDTO getSessionUserInfo() {
        return (SysUserRespDTO) StpUtil.getTokenSession().get(SaSession.USER);
    }

    /**
     * 获取当前登录用户的角色权限信息
     *
     * @return 用户角色权限信息
     */
    @Override
    public SysUserRolePermissionDTO getSysUserRolePermissionBySessionUser() {
        SysUserRespDTO sysUserRespDTO = getSessionUserInfo();
        return sysUserApi.getUserRolePermissionByUsername(sysUserRespDTO.getUsername());
    }

    @Override
    public void logout() {
        StpUtil.logout();
    }

    public static void main(String[] args) {
        // 原始密码
        String password = "123456";
        String salt = BCrypt.gensalt();
        System.out.println("salt:" + salt);
        // 生成盐值并对密码进行加密
        String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());


        System.out.println("加密后的密码: " + hashedPassword);

        if (BCrypt.checkpw("jisai123", hashedPassword)) {
            System.out.println("密码验证成功");
        } else {
            System.out.println("密码验证失败");
        }
    }
}
